<template>
  <div class="content" v-loading="submitBtn">
    <div class="scroll-view-box">
      <el-form label-width="120px" :model="formData" :rules="formRules" ref="elFrom" label-position="top">
        <el-form-item label="案例图片" prop="file">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in formData.file" :key="index">
              <div class="el-icon-delete-box" @click="delFile(index)">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="item.url" />
              </el-tooltip>
            </div>
            <el-upload multiple class="avatar-uploader" action="#" accept="image/*" :show-file-list="false"
              :auto-upload="false" list-type="picture-card" :on-change="changeFile">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="案例标题" prop="title">
          <el-input v-model="formData.title" placeholder="输入案例标题" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="案例品牌" prop="brandIdx">
          <el-select filterable v-model="formData.brandIdx" placeholder="请选择案例品牌" clearable class="input-width">
            <el-option v-for="(item, idx) in brandList" :key="item.id" :label="item.name" :value="idx"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案例详情" prop="info">
          <div class="tinymce-box flex">
            <tinymce @input="tinymceInput" :value="formData.info"></tinymce>
            <div class="html-box">
              <el-carousel height="250px" arrow="never" indicator-position="none" @change="carouselChange">
                <el-carousel-item v-for="(item, idx) in formData.file" :key="idx">
                  <img class="carousel-img" :src="item.url" />
                </el-carousel-item>
              </el-carousel>
              <div class="indicator-num">
                <div class="indicator-num__text">{{ `${carouselIdx}/${formData.file.length}` }}</div>
              </div>
              <div class="notice-title">{{ formData.title ? formData.title : '这是标题' }}</div>
              <div class="flex ac jb" style="padding: 10px 15px;">
                <div class="notice-brand" v-if="formData.brandIdx != ''"
                  :style="{ color: brandList[formData.brandIdx].colour }">{{ brandList[formData.brandIdx].name }}</div>
                <div class="notice-brand" v-else>品牌名称</div>
                <div class="notice-time">1970-01-01</div>
              </div>
              <div style="height: 10px;background-color: #F8F8F8;"></div>
              <div class="tips">案例详情</div>
              <div class="notice-content" v-html="formData.info"></div>
            </div>

          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import Tinymce from "@/components/tinymce/tinymce";
import miniApi from '@/api/mini'
import brandApi from "@/api/brandApi";

export default {
  components: {
    Tinymce
  },
  data() {
    return {
      loading: false,
      editType: 'add',
      richText: '',
      brandList: [],
      formData: {
        id: '',
        file: [],
        brandIdx: '',
        title: '',
        info: '',
        file_id_arr: [],
      },
      formRules: {
        file: [{
          required: true,
          message: "请上传案例图片",
          trigger: "change",
        }],
        title: [{
          required: true,
          message: "请输入公告标题",
          trigger: "change",
        }],
        brandIdx: [{
          required: true,
          message: "请选择品牌",
          trigger: "change",
        }],
        info: [{
          required: true,
          message: "请输入公告详情",
          trigger: "change",
        }],
      },
      submitBtn: false,
      carouselIdx: 0,
    };
  },
  computed: {
  },
  mounted() {
    this.getBrandList(); //品牌

    let id = this.$route.query.sn
    if (id) {
      this.formData.id = id
    }
  },
  methods: {
    carouselChange(e) {
      this.carouselIdx = e + 1
    },
    changeFile(e) {
      this.formData.file.push(e)
    },
    delFile(idx) {
      let fileList = this.formData.file
      if (fileList[idx].rew) {
        this.formData.file.splice(idx, 1)
      } else {
        this.formData.file_id_arr.push(fileList[idx].id)
        this.formData.file.splice(idx, 1)
      }

    },
    tinymceInput(e) {
      const regex = new RegExp('img', 'gi')
      e = e.replace(regex, `img style="max-width:100%;object-fit: cover;"`)
      this.formData.info = e;
    },
    // 提交
    saveSubmit() {
      this.$refs['elFrom'].validate((valid) => {
        if (valid) {
          let formData = this.formData
          this.submitBtn = true;
          if (this.editType == 'add') {
            let obj = {
              title: formData.title,
              content: formData.info,
              brand_id: this.brandList[formData.brandIdx].id,
              file_type: 1,
            }
            let newFormData = new FormData();
            formData.file.forEach(item => {
              if (item.raw) {
                newFormData.append('case_image[]', item.raw);
              }
            })
            // 添加
            newFormData.append('data', JSON.stringify(obj));

            miniApi.addCase(newFormData).then(res => {
              console.log(res, '新增案例')
              if (res.code == 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.cancelFunc()
              } else {
                this.$message.error(res.message);
              }
              this.submitBtn = false;
            })
          } else {
            let obj = {
              id: formData.id,
              title: formData.title,
              content: formData.info,
              brand_id: this.brandList[formData.brandIdx].id,
              file_type: 1,
              file_id_arr: formData.file_id_arr
            }
            let newFormData = new FormData();
            formData.file.forEach(item => {
              if (item.raw) {
                newFormData.append('case_image[]', item.raw);
              }
            })
            // 添加
            newFormData.append('data', JSON.stringify(obj));
            miniApi.updCase(newFormData).then(res => {
              console.log(res, '更新案例')
              if (res.code == 200) {
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
                this.cancelFunc()
              } else {
                this.$message.error(res.message);
              }
              this.submitBtn = false;
            })
          }
        } else {
          return false;
        }
      });
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },

    getBrandList() {
      brandApi.getBrandList({
        page: 1,
        num: 9999,
        keyword: "",
      }).then((res) => {
        console.log(res, "品牌列表");
        if (res.code == 200) {
          this.brandList = res.data.list;

          if (this.formData.id) {
            this.getInfo(this.formData.id)
          }

        }
      }).catch(() => { });

    },
    getInfo(id) {
      miniApi.getConfigDetails({ id }).then(res => {
        console.log(res, '案例详情')
        if (res.code == 200) {
          let case_file = []
          res.data.admin_case_list.map(item => {
            case_file.push({
              id: item.id,
              raw: '',
              url: item.file_url
            })
          })
          let brandIdx = ''
          this.brandList.map((item, index) => {
            if (item.id == res.data.brand_id) {
              brandIdx = index
            }
          })
          this.formData = {
            id,
            file: case_file,
            brandIdx,
            title: res.data.title,
            info: res.data.content,
            file_id_arr: [],
          }
          this.editType = 'update'

        }
        this.loading = false
      })
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/addPage.scss";

.tinymce-box {
  width: 100%;
  margin-bottom: 20px;

  .html-box {
    width: 375px;
    height: 600px;
    border: 1px solid #cccccc;
    margin-left: 20px;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: hidden;
  }

  ::v-deep .tox-tinymce {
    min-height: 600px;
  }
}

.notice-title {
  font-size: 17px;
  font-weight: 600;
  padding: 10px 15px 0;
}

.notice-time {
  font-size: 13px;
  color: #999999;
}

::v-deep .el-form-item__content {
  line-height: normal;
}

::v-deep .el-carousel__container {
  background-color: #d3dce6;
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
  pointer-events: none;
}

.tips {
  font-size: 15px;
  padding: 10px 15px;
}

.indicator-num {
  position: absolute;
  top: 220px;
  right: 20px;
  z-index: 99;
  padding: 2px 0;
  background-color: rgba(0, 0, 0, 0.35);
  border-radius: 100px;
  width: 35px;
  display: flex;
  flex-direction: row;
  justify-content: center;

  .indicator-num__text {
    color: #FFFFFF;
    font-size: 12px;
  }
}
</style>